// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogLevelExtensions.cs" company="AzureContrib (Open source library http://azurecontrib.codeplex.com)">
//   Microsoft Public License (Ms-PL)
// </copyright>
// <summary>
//   Extensions on <see cref="LogLevel"/> transformations.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Globalization;

using AzureContrib.WindowsAzure.Properties;

namespace AzureContrib.WindowsAzure.Diagnostics
{
	/// <summary>
	/// Extensions on <see cref="LogLevel"/> transformations.
	/// </summary>
	public static class LogLevelExtensions
	{
		/// <summary>
		/// Convert a <see cref="string"/> to a <see cref="LogLevel"/>.
		/// </summary>
		/// <param name="level">The <see cref="string"/> to convert.</param>
		/// <returns>The parsed <see cref="LogLevel"/>.</returns>
		public static LogLevel ParseLogLevel(this string level)
		{
			LogLevel logLevel;
			if (!TryParseLogLevel(level, out logLevel))
			{
				throw new FormatException(Strings.NotALogLevel.F(level));
			}

			return logLevel;
		}

		/// <summary>
		/// Try convert a <see cref="string"/> to a <see cref="LogLevel"/>.
		/// </summary>
		/// <param name="level">The <see cref="string"/> to convert.</param>
		/// <param name="logLevel">The parsed <see cref="LogLevel"/>.</param>
		/// <returns>True if the <paramref name="level"/> was a <see cref="LogLevel"/>.</returns>
		/// <remarks>When return is false <paramref name="logLevel"/> is <see cref="LogLevel.Off"/>.</remarks>
		public static bool TryParseLogLevel(this string level, out LogLevel logLevel)
		{
			if (string.IsNullOrEmpty(level))
			{
				logLevel = LogLevel.Off;
				return false;
			}

			if (level.ToUpper(CultureInfo.InvariantCulture) == "INFO")
			{
				logLevel = LogLevel.Information;
				return true;
			}

			level = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(level);

			try
			{
				logLevel = (LogLevel)Enum.Parse(typeof(LogLevel), level);
			}
			catch (ArgumentException e)
			{
				if (e.Message.StartsWith("Requested value '", StringComparison.Ordinal) && e.Message.EndsWith("' was not found.", StringComparison.Ordinal))
				{
					logLevel = LogLevel.Off;
					return false;
				}

				throw;
			}

			return true;
		}
	}
}